package com.woniuxy.course.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.woniuxy.course.entity.TeacherInfo;
import com.woniuxy.course.mapper.TeacherInfoMapper;
import com.woniuxy.course.service.TeacherInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author cyh
 * @since 2020-08-03
 */
@Service
public class TeacherInfoServiceImpl extends ServiceImpl<TeacherInfoMapper, TeacherInfo> implements TeacherInfoService {
    @Autowired
    private TeacherInfoMapper teacherInfoMapper;
    //修改老师信息
    @Override
    public Integer updateTeacherInfo(TeacherInfo teacherInfo) {
        int i = teacherInfoMapper.updateById(teacherInfo);
        return i;
    }

    @Override
    public TeacherInfo findTeacherInfoById(Long id) {
        TeacherInfo teacherInfo = teacherInfoMapper.selectById(id);
        return teacherInfo;
    }
    //网络上传文件

    @Transactional
    public String upload(MultipartFile file) {
        // Endpoint以杭州为例，其它Region请按实际情况填写。
        String endpoint = "https://oss-cn-shanghai.aliyuncs.com";
        // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录RAM控制台创建RAM账号。
        String accessKeyId = "LTAI4G4ZNMdvr9ZBBesGncKK";
        String accessKeySecret = "vKTiLbiRojXKZFKYszWNRSZTx7e3us";
        String bucketName = "course-0723";
        String filename = file.getOriginalFilename();
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        filename = uuid + filename;
        //获取当前日期
        String datePath = new DateTime().toString("yyyy/MM/dd");
        filename = datePath + "/" + filename;
        try {
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            // 上传文件流。
            InputStream inputStream = file.getInputStream();
            ossClient.putObject(bucketName, filename, inputStream);

            // 关闭OSSClient。
            ossClient.shutdown();

            String url = "https://" + bucketName + "." + endpoint + "/" + filename;

            return url;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }


    }
}
